<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>巷陌发现 - 小众店铺推荐</title>
    <link rel="stylesheet" href="../static/layui/css/layui.css">
    <script src="../static/js/jquery.js"></script>
    <script src="../static/js/jquery.cookie.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
            background-color: #f5f7fa;
            color: #333;
            line-height: 1.6;
            padding: 20px 0;
        }

        /* 内容区域样式 */
        .content-container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 0 20px;
        }

        /* 搜索区域 */
        .search-section {
            background-color: white;
            border-radius: 12px;
            padding: 25px;
            margin-bottom: 25px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.05);
            text-align: center;
        }

        .search-box {
            display: flex;
            max-width: 600px;
            margin: 0 auto;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.08);
            border-radius: 30px;
            overflow: hidden;
            transition: box-shadow 0.3s;
        }

        .search-box:focus-within {
            box-shadow: 0 4px 15px rgba(106, 17, 203, 0.15);
        }

        .search-input {
            flex: 1;
            border: none;
            padding: 15px 25px;
            font-size: 16px;
            outline: none;
            background: #f8f9fa;
        }

        .search-btn {
            background: linear-gradient(45deg, #6a11cb 0%, #2575fc 100%);
            color: white;
            border: none;
            padding: 0 30px;
            cursor: pointer;
            font-size: 16px;
            transition: background-color 0.3s;
        }

        .search-btn:hover {
            background: linear-gradient(45deg, #5a0dc8 0%, #1a69e0 100%);
        }

        /* 分类区域 */
        .category-section {
            background-color: white;
            border-radius: 12px;
            padding: 25px;
            margin-bottom: 25px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.05);
        }

        .section-title {
            font-size: 20px;
            color: #333;
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 2px solid #f0f0f0;
            display: flex;
            align-items: center;
        }

        .section-title i {
            margin-right: 10px;
            color: #6a11cb;
        }

        .category-tags {
            display: flex;
            flex-wrap: wrap;
            gap: 12px;
        }

        .category-tag {
            background-color: #f8f9fa;
            border: 1px solid #eaeaea;
            padding: 8px 20px;
            border-radius: 20px;
            font-size: 14px;
            cursor: pointer;
            transition: all 0.3s;
            display: flex;
            align-items: center;
        }

        .category-tag i {
            margin-right: 6px;
            opacity: 0;
            transition: opacity 0.3s;
        }

        .category-tag:hover i,
        .category-tag.active i {
            opacity: 1;
        }

        .category-tag:hover, .category-tag.active {
            background: linear-gradient(45deg, #6a11cb 0%, #2575fc 100%);
            color: white;
            border-color: #6a11cb;
            transform: translateY(-2px);
        }

        /* 店铺列表 */
        .shop-list-section {
            background-color: white;
            border-radius: 12px;
            padding: 25px;
            margin-bottom: 30px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.05);
        }

        .shop-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(270px, 1fr));
            gap: 25px;
            margin-top: 20px;
        }

        .shop-card {
            background-color: white;
            border-radius: 12px;
            overflow: hidden;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.05);
            transition: all 0.3s ease;
            border: 1px solid #f0f0f0;
            position: relative;
        }

        .shop-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 12px 20px rgba(106, 17, 203, 0.1);
        }

        .shop-image-container {
            position: relative;
            overflow: hidden;
        }

        .shop-image {
            width: 100%;
            height: 180px;
            object-fit: cover;
            transition: transform 0.5s ease;
        }

        .shop-card:hover .shop-image {
            transform: scale(1.05);
        }

        .shop-collect {
            position: absolute;
            top: 15px;
            right: 15px;
            width: 36px;
            height: 36px;
            background-color: rgba(255, 255, 255, 0.9);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            transition: all 0.3s;
            color: #999;
        }

        .shop-collect:hover, .shop-collect.active {
            background: linear-gradient(45deg, #ff5e62 0%, #ff9966 100%);
            color: white;
        }

        .shop-info {
            padding: 20px;
        }

        .shop-name {
            font-size: 18px;
            font-weight: bold;
            margin-bottom: 8px;
            color: #333;
            transition: color 0.3s;
        }

        .shop-card:hover .shop-name {
            color: #6a11cb;
        }

        .shop-category {
            color: #6a11cb;
            font-size: 14px;
            margin-bottom: 12px;
            display: flex;
            align-items: center;
        }

        .shop-category i {
            margin-right: 5px;
        }

        .shop-desc {
            color: #666;
            font-size: 14px;
            line-height: 1.6;
            margin-bottom: 15px;
            height: 68px;
            overflow: hidden;
            position: relative;
        }

        .shop-desc::after {
            content: '';
            position: absolute;
            bottom: 0;
            left: 0;
            width: 100%;
            height: 30px;
            background: linear-gradient(transparent, white);
            opacity: 0;
            transition: opacity 0.3s;
        }

        .shop-card:hover .shop-desc::after {
            opacity: 1;
        }

        .shop-footer {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding-top: 10px;
            border-top: 1px dashed #f0f0f0;
        }

        .shop-rating {
            color: #FF9800;
            font-weight: bold;
            display: flex;
            align-items: center;
        }

        .view-detail-btn {
            background: linear-gradient(45deg, #6a11cb 0%, #2575fc 100%);
            color: white;
            border: none;
            padding: 8px 15px;
            border-radius: 4px;
            font-size: 14px;
            cursor: pointer;
            transition: all 0.3s;
        }

        .view-detail-btn:hover {
            background: linear-gradient(45deg, #5a0dc8 0%, #1a69e0 100%);
            transform: translateY(-2px);
        }

        /* 空状态样式 */
        .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: #999;
        }

        .empty-icon {
            font-size: 60px;
            margin-bottom: 20px;
            color: #eee;
        }

        .empty-text {
            font-size: 18px;
            margin-bottom: 15px;
        }

        .empty-subtext {
            font-size: 14px;
            margin-bottom: 30px;
        }

        .empty-action {
            background: linear-gradient(45deg, #6a11cb 0%, #2575fc 100%);
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 4px;
            cursor: pointer;
        }

        /* 分页样式 */
        .pagination-container {
            margin-top: 30px;
            text-align: center;
            padding: 15px 0;
        }

        /* 轮播图样式 */
        .shop-carousel {
            position: relative;
        }

        .carousel-imgs {
            width: 100%;
            height: 180px;
            position: relative;
            overflow: hidden;
        }

        .carousel-dots {
            position: absolute;
            bottom: 10px;
            left: 50%;
            transform: translateX(-50%);
            display: flex;
            gap: 8px;
        }

        .dot {
            width: 8px;
            height: 8px;
            border-radius: 50%;
            background-color: rgba(255, 255, 255, 0.6);
            cursor: pointer;
            transition: all 0.3s;
        }

        .dot.active {
            background-color: white;
            width: 24px;
            border-radius: 4px;
        }

        /* 响应式设计 */
        @media (max-width: 992px) {
            .shop-grid {
                grid-template-columns: repeat(2, 1fr);
            }
        }

        @media (max-width: 768px) {
            .shop-grid {
                grid-template-columns: 1fr;
            }

            .search-box {
                flex-direction: column;
                border-radius: 12px;
            }

            .search-input {
                border-radius: 12px 12px 0 0;
            }

            .search-btn {
                border-radius: 0 0 12px 12px;
                padding: 12px;
            }

            .category-tag {
                padding: 6px 15px;
                font-size: 13px;
            }
        }
    </style>
</head>
<body>
<!-- 内容区域 -->
<div class="content-container">
    <!-- 搜索区域 -->
    <div class="search-section">
        <div class="search-box">
            <input type="text" class="search-input" id="searchShop" placeholder="请输入店铺名或商品名称">
            <button class="search-btn" onclick="searchShop(event)">搜索</button>
        </div>
    </div>

    <!-- 分类区域 -->
    <div class="category-section">
        <h2 class="section-title"><i class="layui-icon layui-icon-form"></i> 热门分类</h2>
        <div class="category-tags" id="tagList">
            <!-- 标签将由JS动态生成 -->
        </div>
    </div>

    <!-- 店铺列表 -->
    <div class="shop-list-section">
        <h2 class="section-title"><i class="layui-icon layui-icon-star"></i> 首页推荐店铺</h2>
        <div class="shop-grid" id="shopList">
            <!-- 店铺卡片将由JS动态生成 -->
        </div>

        <!-- 分页控件 -->
        <div class="pagination-container">
            <div id="pagination" class="layui-box layui-laypage layui-laypage-default"></div>
        </div>
    </div>
</div>

<script src="../static/layui/layui.js"></script>
<script>
    let page = 1; // 当前页码，与后端保持一致
    const pageSize = 6; // 每页显示数量
    let total = 0; // 总记录数
    let isLoading = false; // 防止重复请求
    $(function() {
        // 初始化时阻止表单默认提交行为
        $(document).on('submit', 'form', function(e) {
            e.preventDefault();
        });

        init();
    });

    // 修改init函数中的初始化
    function init() {
        page = 1; // 使用page变量
        initShop(null, null, true);
        initTag();
    }


    function initShop(data, activetag, isReset) {
        if (isLoading) return;
        isLoading = true;

        $('#shopList').html('<div style="text-align:center;padding:50px;"><i class="layui-icon layui-icon-loading layui-icon-loading-1"></i> 加载中...</div>');

        console.log(`请求参数: page=${page}, pageSize=${pageSize}, name=${data}, tagName=${activetag}`);

        $.ajax({
            url: "/homepage/findAll",
            type: "post",
            data: {
                name: data,
                tagName: activetag,
                page: page,
                pageSize: pageSize
            },
            async: true,
            cache: false,
            success: function(res) {
                console.log("后端返回数据:", res);
                if (res.code == 200 && res.data) {
                    const { list, total: totalCount } = res.data;
                    total = totalCount;
                    console.log(`第${page}页数据，共${total}条，当前页${list.length}条`);
                    renderShopList(list, isReset);
                    renderPagination();
                } else {
                    $('#shopList').html('<div class="empty-state"><div class="empty-icon"><i class="layui-icon layui-icon-error"></i></div><div class="empty-text">数据加载失败</div><button class="empty-action" onclick="init()">重试</button></div>');
                }
            },
            error: function(xhr) {
                console.error("请求错误:", xhr);
                $('#shopList').html('<div class="empty-state"><div class="empty-icon"><i class="layui-icon layui-icon-error"></i></div><div class="empty-text">网络错误</div><button class="empty-action" onclick="init()">重试</button></div>');
            },
            complete: function() {
                isLoading = false;
            }
        });
    }

    // 渲染分页控件（关键修复：确保分页点击时page变量被正确更新）
    function renderPagination() {
        if (typeof layui === 'undefined' || !layui.laypage) {
            setTimeout(renderPagination, 100);
            return;
        }

        const laypage = layui.laypage;
        $('#pagination').empty(); // 清空旧分页

        laypage.render({
            elem: 'pagination',
            count: total,
            limit: pageSize,
            curr: page, // 确保当前页码与page变量一致
            limits: [6, 12, 18],
            layout: ['prev', 'page', 'next', 'count', 'limit', 'skip'],
            jump: function(obj, first) {
                if (!first) {
                    if (isLoading) return;
                    page = obj.curr; // 点击分页后，更新page变量为目标页码
                    console.log(`分页跳转: 从${obj.prev}页到${page}页`);
                    searchShop();
                }
            }
        });
    }

    // 搜索逻辑（确保分页时携带正确的page参数）
    function searchShop() {
        const tag = document.querySelector('.category-tag.active');
        const data = document.getElementById('searchShop').value.trim();
        const activetag = tag && tag.textContent.trim() !== "全部" ? tag.textContent.trim() : null;
        // 此处不重置page，由分页逻辑控制
        initShop(data, activetag, true);
    }

    function initTag() {
        $.ajax({
            url: "/homepage/findTags",
            type: "post",
            success: function(res) {
                console.log("标签数据:", res);
                if (res.code == 200) {
                    renderTagList(res.data);
                }
            },
            error: function(res) {
                alert("标签初始化失败!");
            }
        });
    }

    // 渲染店铺列表
    function renderShopList(data, isReset) {
        const shopList = document.getElementById('shopList');
        let html = '';

        // 如果是重置列表，先清空现有内容
        if (isReset) {
            shopList.innerHTML = '';
        }

        if (data.length === 0) {
            html = `
                    <div class="empty-state">
                        <div class="empty-icon"><i class="layui-icon layui-icon-search"></i></div>
                        <div class="empty-text">未找到相关店铺</div>
                        <div class="empty-subtext">尝试更换关键词或分类进行搜索</div>
                        <button class="empty-action" onclick="resetSearch()">查看全部店铺</button>
                    </div>
                `;
            shopList.innerHTML = html;
        } else {
            data.forEach(shop => {
                // 处理轮播图URL
                const bannerUrlsStr = String(shop.bannerUrls || "[]");
                const bannerUrls = JSON.parse(bannerUrlsStr);

                html += `
                        <div class="shop-card">
                            <div class="shop-image-container">
                                <div class="shop-carousel" data-banner-urls='${JSON.stringify(bannerUrls)}'>
                                    <!-- 轮播图由JS动态生成 -->
                                </div>
                            </div>
                            <div class="shop-info">
                                <h3 class="shop-name">${shop.name}</h3>
                                <div class="shop-category">
                                    <i class="layui-icon layui-icon-form"></i>${shop.tagName || '未分类'}
                                </div>
                                <p class="shop-desc">${shop.desc || '暂无店铺描述'}</p>
                                <div class="shop-footer">
                                    <div class="shop-rating">
                                        <i class="layui-icon layui-icon-rate"></i> ${shop.rating || '暂无评分'}
                                    </div>
                                    <button class="view-detail-btn" onclick="goToDetail(${shop.id})">查看详情</button>
                                </div>
                            </div>
                        </div>
                    `;
            });

            shopList.innerHTML = html;
            initCarousels(); // 初始化轮播图
        }
    }

    // 渲染标签
    function renderTagList(data) {
        const tagList = document.getElementById('tagList');
        let html = `
                <div class="category-tag active" onclick="setActiveTag(this, event)">
                    <i class="layui-icon layui-icon-check"></i>全部
                </div>
            `;

        if (data && data.length > 0) {
            data.forEach(tag => {
                html += `
                        <div class="category-tag" onclick="setActiveTag(this, event)">
                            <i class="layui-icon layui-icon-check"></i>${tag.tagName}
                        </div>
                    `;
            });
        }

        tagList.innerHTML = html;
    }

    // 根据标签筛选店铺
    function setActiveTag(element, event) {
        // 阻止事件冒泡和默认行为
        if (event) {
            event.preventDefault();
            event.stopPropagation();
        }

        document.querySelectorAll('.category-tag').forEach(tag => {
            tag.classList.remove('active');
        });
        element.classList.add('active');
        searchShop();
    }
    // 重置搜索
    function resetSearch() {
        // 清空搜索框
        document.getElementById('searchShop').value = '';
        // 激活"全部"标签
        document.querySelectorAll('.category-tag')[0].click();
    }

    // 跳转到详情页
    function goToDetail(id) {
        window.location.href = "/homepage/goToDetail?id=" + id;
    }

    // 初始化轮播图
    function initCarousels() {
        const carousels = document.querySelectorAll('.shop-carousel');
        carousels.forEach(carousel => {
            const bannerUrls = JSON.parse(carousel.dataset.bannerUrls);

            if (bannerUrls.length === 0) {
                carousel.innerHTML = `
                        <img src="https://picsum.photos/400/300" alt="店铺默认图片" class="shop-image">
                    `;
                return;
            }

            // 生成轮播结构
            let carouselHtml = `
                    <div class="carousel-imgs">
                `;

            bannerUrls.forEach((url, index) => {
                carouselHtml += `
                        <img src="${url}" alt="店铺轮播图${index+1}" class="shop-image"
                             style="${index > 0 ? 'display:none;' : ''}" loading="lazy">
                    `;
            });

            carouselHtml += `
                    </div>
                    <div class="carousel-dots">
                `;

            bannerUrls.forEach((_, index) => {
                carouselHtml += `
                        <span class="dot ${index === 0 ? 'active' : ''}" data-index="${index}"></span>
                    `;
            });

            carouselHtml += `</div>`;
            carousel.innerHTML = carouselHtml;

            // 自动轮播
            let currentIndex = 0;
            const interval = setInterval(() => {
                currentIndex = (currentIndex + 1) % bannerUrls.length;
                changeCarousel(carousel, currentIndex);
            }, 3000);

            // 点击圆点切换轮播
            carousel.querySelectorAll('.dot').forEach(dot => {
                dot.addEventListener('click', () => {
                    clearInterval(interval);
                    currentIndex = parseInt(dot.dataset.index);
                    changeCarousel(carousel, currentIndex);

                    // 重新开始自动轮播
                    setInterval(() => {
                        currentIndex = (currentIndex + 1) % bannerUrls.length;
                        changeCarousel(carousel, currentIndex);
                    }, 3000);
                });
            });
        });
    }

    // 切换轮播图
    function changeCarousel(carousel, index) {
        const imgs = carousel.querySelectorAll('.carousel-imgs img');
        const dots = carousel.querySelectorAll('.dot');

        imgs.forEach((img, i) => {
            img.style.display = i === index ? 'block' : 'none';
        });

        dots.forEach((dot, i) => {
            dot.classList.toggle('active', i === index);
        });
    }
</script>
</body>
</html>